package StatuSync::Daemon;
use strict;

use AnyEvent;
use AnyEvent::Twitter::Stream;
#$AnyEvent::Twitter::Stream::STREAMING_SERVER = 'localhost:33008';

use base qw(StatuSync::Log);
use WWW::VKontakte::API;
use StatuSync::User;

use base qw(Class::Accessor);

#__PACKAGE__->mk_accessors(qw());

sub new {
	my $class = shift;
	my $self = $class->SUPER::new(@_);
	$self->debug();

	return $self;
}

sub init {
	my $self = shift;
	$self->debug();
	$self->reload_config;
	$self->{signal_handler} = AnyEvent->signal( signal => "HUP", cb => sub {
		$self->debug( HUP => @_ );
		$self->{_reload_config} = 1;
	} );
	$self->{timer_handler} = AnyEvent->timer( interval => 10, cb => sub {
#		$self->debug( timer => @_ );
		$self->{_reload_config} and $self->reload_config->init_stream;
	} );
	$self->init_stream;
	return $self;
}

sub init_stream {
	my $self = shift;
	$self->debug($self->{follow});
	undef $self->{twitter_stream};
	$self->{twitter_stream} = AnyEvent::Twitter::Stream->new(
		username => $self->{twitter}{username},
		password => $self->{twitter}{password},
		method   => "filter",
		follow   => join(",", map { $_->tw_id } @{ $self->{follow} }) || 1, # FIXME what to do if noone to follow?
		on_tweet => sub {
			my $tweet = shift;
			$self->post_status( $tweet );
		},
		on_keepalive => sub {
			$self->debug(ping => @_);
		},
		on_error => sub {
			$self->error(error => @_);
			$self->init_stream;
		},
		timeout => 60,
	);
	return $self;
}

sub reload_config {
	my $self = shift;
	$self->debug();
	delete $self->{_reload_config};
	$self->{follow} = [ grep { $_->tw_id } StatuSync::User->search() ];
	return $self;
}

sub post_status {
	my $self = shift;
	my $tweet = shift;
	my ($user) = grep { $_->tw_id eq $tweet->{user}{id} } @{ $self->{follow} };
	$self->debug($tweet, $user);
	$user
		and $tweet->{text} !~ /^\@\w|RT\s+\@\w/
		or return $self;
	if ($user->vk_email && $user->vk_password) {
		WWW::VKontakte::API->new({
			email => $user->vk_email,
			password => $user->vk_password,
		})->login->set_activity( $tweet->{text} )->logout;
		$self->debug('set_activity');
	}
	return $self;
}


1;

